<script setup lang="ts">
import {ref, watch} from 'vue'
import SelectMedicinePopover from "@/component/select-medicine/SelectMedicinePopover.vue";
import {SelectMedicineEmit, SelectMedicineInput} from "@/component/select-medicine/types.ts";
import {MedicineData} from "@/api/medicine";

const props = withDefaults(defineProps<SelectMedicineInput>(), {
  isAuto: true,
  width: 1200,
  triggerKeys: () => {
    return ['Esc']
  }
})

const model = defineModel<string | object>({default: ''})
const value = ref<string>('')
const $emit = defineEmits<SelectMedicineEmit>()

watch(
    () => model.value,
    () => {
      if (typeof model.value === 'string') {
        value.value = model.value
      } else {
        const data = model.value as Record<string, any>
        debugger
        if (props.dataProps) {
          const keys = Object.keys(props.dataProps)
          if (keys.length > 0) {
            const prop = props.dataProps[props.prop]
            value.value = data[prop]
          } else {
            value.value = data[props.prop]
          }
        } else {
          value.value = data[props.prop]
        }
      }
    },
    {immediate: true}
)

const handleSelectChange = (row: MedicineData) => {
  value.value = row[props.prop]
  if (typeof model.value === 'string') {
    model.value = row[props.prop]
  } else {
    const data = model.value as Record<string, any>
    if (props.dataProps) {
      const keys = Object.keys(props.dataProps)
      if (keys.length > 0) {
        keys.forEach(key => {
          const prop = props.dataProps![key]
          data[prop] = row[key]
        })
      } else {
        data[props.prop] = row[props.prop]
      }
    } else {
      data[props.prop] = row[props.prop]
    }
  }
  $emit('selectionChange', row)
}
</script>

<template>
  <div class="select-medicine-input">
    <SelectMedicinePopover
        v-bind="Object.assign({value}, props, $attrs)"
        @selection-change="handleSelectChange"
    >
      <template #reference>
        <el-input v-model="value" />
      </template>
    </SelectMedicinePopover>
  </div>
</template>

<style scoped>

</style>